package com.tebiecloud.yunst.server.yunstservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.allinpay.yunst.sdk.YunClient;
import com.allinpay.yunst.sdk.bean.YunRequest;
import com.allinpay.yunst.sdk.util.RSAUtil;
import com.tebiecloud.yunst.client.model.yunst.CollectPay;
import com.tebiecloud.yunst.client.model.yunst.IDGenerator;
import com.tebiecloud.yunst.client.model.yunst.Reciever;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class YunStServiceImpl implements YunStService{

	@Value("${tebiecloud.yunst.accountSetNo}")
	private String accountSetNo;

	@Value("${tebiecloud.yunst.webParamUrl}")
	private String webParamUrl;

	@Value("${tebiecloud.yunst.normAccountSetNo}")
	private String normAccountSetNo;

	@Override
	public String createMember(String bizUserId, String memberType, String source) {
		// TODO Auto-generated method stub
		log.info("================MemberAPI: createMember begin================");
		long start = System.currentTimeMillis();
		String req = "";
		final YunRequest request = new YunRequest("MemberService", "createMember");
		if(bizUserId == null || "auto".equalsIgnoreCase(bizUserId))
			bizUserId = IDGenerator.generateGUID();
		
		request.put("bizUserId", bizUserId);
		request.put("memberType", memberType);
		request.put("source", source);
		log.info("[bizUserId="+bizUserId+", memberType="+memberType+", source="+source+"]");
		try {
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			req = status;
			if(status != null && status.equals("OK")) {
				log.info("API[createMember SUCCESS!]");
			} else {
				log.error("API_ERROR[createMember RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: createMember end================[elapse: "+ elapse+" ms]");
		if(req.equals("OK")) {
			return bizUserId;
		}else {
			return "0";
		}
	}

	@Override
	public Map<String,String> sendVerificationCode(String bizUserId, String phone, String verificationCodeType) {
		// TODO Auto-generated method stub
		Map<String,String> resultMap = new HashMap<String,String>();
		log.info("================MemberAPI:  sendVerificationCode  begin================");
		long start = System.currentTimeMillis();
		final YunRequest request = new YunRequest("MemberService", "sendVerificationCode");
		request.put("bizUserId", bizUserId);
		request.put("phone", phone);
		request.put("verificationCodeType", 9L);
		log.info("[bizUserId="+bizUserId+", phone="+phone+", verificationCodeType=9]");
		String res = "";
		try {
			res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				resultMap.put("status","OK");
				resultMap.put("code","0");
				resultMap.put("message","SUCCESS");
				log.info("API[sendVerificationCode SUCCESS!]");
			} else {
				resultMap.put("status","error");
				resultMap.put("code",resp.getString("errorCode"));
				resultMap.put("message",resp.getString("message"));
				log.error("API_ERROR[sendVerificationCode RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: sendVerificationCode end================[elapse: "+ elapse+" ms]");
		return resultMap;
	}

	@Override
	public Map<String, String> bindPhone(String bizUserId, String phoneNo, String verificationCode) {
		// TODO Auto-generated method stub
		Map<String,String> resultMap = new HashMap<String,String>();
		log.info("================MemberAPI: bindPhone begin================");
		long start = System.currentTimeMillis();
		final YunRequest request = new YunRequest("MemberService", "bindPhone");
		String res = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("phone", phoneNo);
			if(verificationCode!=null) {
				request.put("verificationCode", verificationCode);
			}else {
				request.put("verificationCode", "11111");  //TODO:测试环境需要增加判断逻辑
			}
			res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				resultMap.put("status","OK");
				resultMap.put("code","0");
				resultMap.put("message","SUCCESS");
				log.info("API[bindPhone SUCCESS!]");
			} else {
				resultMap.put("status","error");
				resultMap.put("code",resp.getString("errorCode"));
				resultMap.put("message",resp.getString("message"));
				log.error("API_ERROR[bindPhone RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: bindPhone end================[elapse: "+ elapse+" ms]");
		return resultMap;
	}
	
	@Override
	public String changeBindPhone(String bizUserId, String phone, String newPhone, String verificationCode) {
		// TODO Auto-generated method stub
		log.info("================MemberAPI: changeBindPhone begin================");
		long start = System.currentTimeMillis();
		final YunRequest request = new YunRequest("MemberService", "changeBindPhone");
		String res = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("oldPhone", phone);
			request.put("newPhone", newPhone);
			if(verificationCode!=null) {
				request.put("newVerificationCode", verificationCode);
			}else {
				request.put("newVerificationCode", "11111");  //TODO:测试环境需要增加判断逻辑
			}
			res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				log.info("API[bindPhone SUCCESS!]");
			} else {
				log.error("API_ERROR[bindPhone RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: bindPhone end================[elapse: "+ elapse+" ms]");
		return res;
	}

	@Override
	public Map<String,String> setRealName(String bizUserId, String name,String identityNo) {
		// TODO Auto-generated method stub
		Map<String,String> resultMap = new HashMap<String,String>();
		log.info("================MemberAPI: setRealName begin================");
		long start = System.currentTimeMillis();
		final YunRequest request = new YunRequest("MemberService", "setRealName");
		String res = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("isAuth", "true");
			request.put("name", name);
			request.put("identityType", 1);//默认是身份证类型
			request.put("identityNo", RSAUtil.encrypt(identityNo));
			res = YunClient.request(request);
			
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				resultMap.put("status","OK");
				resultMap.put("code","0");
				resultMap.put("message","SUCCESS");
				log.info("API[setRealName SUCCESS!]");
			} else {
				resultMap.put("status","error");
				resultMap.put("code",resp.getString("errorCode"));
				resultMap.put("message",resp.getString("message"));
				log.error("API_ERROR[setRealName RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: setRealName end================[elapse: "+ elapse+" ms]");	
		return resultMap;
	}
	
	@Override
	public String signContract(String bizUserId,String jumpUrl, String backUrl) {
		// TODO Auto-generated method stub
		log.info("================MemberAPI: signContract begin================");
		long start = System.currentTimeMillis();
		final YunRequest request = new YunRequest("MemberService", "signContract");
		String webUrl = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("memberType", "3");//默认是个人会员
			request.put("jumpUrl", jumpUrl);
			request.put("backUrl", backUrl);
			request.put("source", "2");//默认手机终端
			
			String res = YunClient.encodeOnce(request);
			webUrl = webParamUrl;
			webUrl += res;
			
			
		} catch (final Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: signContract end================[elapse: "+ elapse+" ms]");
		return webUrl;
		
	}
	
	@Override
	public Map<String,String> applyBindAcct(String bizUserId, String acctType, String acct){
		// TODO Auto-generated method stub
		Map<String,String> resultMap = new HashMap<String,String>();
		log.info("================MemberAPI:  applyBindAcct  begin================");
		long start = System.currentTimeMillis();
		final YunRequest request = new YunRequest("MemberService", "applyBindAcct");
		String res = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("operationType", "set");
			request.put("acctType",acctType);//weChatMiniProgram
			request.put("acct", acct);
			res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				resultMap.put("status","OK");
				resultMap.put("code","0");
				resultMap.put("message","SUCCESS");
				log.info("API[getMemberInfo SUCCESS!]");
			} else {
				resultMap.put("status","error");
				resultMap.put("code",resp.getString("errorCode"));
				resultMap.put("message",resp.getString("message"));
				log.error("API_ERROR[getMemberInfo RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: applyBindAcct end================[elapse: "+ elapse+" ms]");
		return resultMap;
	}
	
	@Override
	public Map<String,String> getMemberInfo(String bizUserId) {
		// TODO Auto-generated method stub
		log.info("================MemberAPI: getMemberInfo begin================");
		long start = System.currentTimeMillis();
		Map<String,String> resultMap = new HashMap<String,String>();
		final YunRequest request = new YunRequest("MemberService", "getMemberInfo");
		try {
			request.put("bizUserId", bizUserId);
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				resultMap.put("status","OK");
				resultMap.put("isSignContract",resp.getJSONObject("signedValue").getJSONObject("memberInfo").getString("isSignContract"));
				log.info("API[getMemberInfo SUCCESS!]");
			} else {
				resultMap.put("status", "error");
				resultMap.put("code", resp.getString("errorCode"));
				resultMap.put("message", resp.getString("message"));
				log.error("API_ERROR[getMemberInfo RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: getMemberInfo end================[elapse: "+ elapse+" ms]");
		return resultMap;
	}

	@Override
	public HashMap<String, String> applyBindBankCard(String bizUserId, String cardPhone, String cardNo,
			String name, String identityNo) {
		// TODO Auto-generated method stub
		log.info("================MemberAPI: applyBindBankCard begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("MemberService", "applyBindBankCard");
		try {
			request.put("bizUserId", bizUserId);
			request.put("phone", cardPhone);// 这个手机号是绑卡银行预留手机，实名支付用
			request.put("cardCheck", 5L);	// 1L 三要素，2L 四要素(默认)
			request.put("cardNo", RSAUtil.encrypt(cardNo));
			request.put("name", name);
			request.put("identityNo", RSAUtil.encrypt(identityNo));
			request.put("identityType", 1); //默认是身份证类型		
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String tranceNum = "";
			String transDate = "";
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				log.info("API[applyBindBankCard SUCCESS!]");
				result.put("status", "OK");
				result.put("code","0");
				result.put("message","SUCCESS");
			} else {
				result.put("status", "error");
				result.put("code",resp.getString("errorCode"));
				result.put("message", resp.getString("message"));
				log.error("API_ERROR[applyBindBankCard RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: applyBindBankCard end================[elapse: "+ elapse+" ms]");	
		return result;
	}

	@Override
	public HashMap<String, String> bindBankCard(String bizUserId, String tranceNum, String transDate, String phone,
			String verificationCode) {
		// TODO Auto-generated method stub
		log.info("================MemberAPI: bindBankCard begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("MemberService", "bindBankCard");
		try {
			request.put("bizUserId", bizUserId);
			request.put("tranceNum", tranceNum);	
			request.put("transDate", transDate);
			request.put("phone", phone);	
			request.put("verificationCode", verificationCode); //TODO smscode
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			result.put("res", res);
			if(status != null && status.equals("OK")) {
				result.put("status", "OK");
				log.info("API[bindBankCard SUCCESS!]");
			} else {
				result.put("status", "ERROR");
				log.error("API_ERROR[bindBankCard RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
		}
		
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberAPI: bindBankCard end================[elapse: "+ elapse+" ms]");	
		return result;
	}

	@Override
	public HashMap<String, String> agentCollectApplySimplify(String payerId,String bizUserId,
			Long amount,String backUrl, String payMethodStr, String wxOpenId,String authCode) {
		// TODO Auto-generated method stub
		log.info("================OrderAPI: agentCollectApplySimplify begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "agentCollectApply");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, 15);
		Date date = calendar.getTime();
		String ordErexpireDatetime = sdf.format(date);
		HashMap<String, Object> payMethod = new HashMap<>();
		String bizOrderNo = "TGDSS" + System.currentTimeMillis();
		
		List<Reciever> recieverList = new ArrayList<Reciever>();
		Reciever reciever = new Reciever();
		reciever.setBizUserId(bizUserId);
		reciever.setAmount(amount);
		recieverList.add(reciever);
		
		String payStatus = "";
		String payFailMessage = "";
		String orderNo = "";
		String payCode = "";
//		String tradeNo = "";
		String payInfo = "";
		String extendInfo = "";
		
		String appId = "";
		String packageStr = "";
		String prepayid = "";
		String nonceStr = "";
		String timeStamp = "";
		String paySign = "";
		String signType = "";
		String limitPay = "no_credit"; //默认不用借贷卡
		String payType = "W02"; //默认不用借贷卡
		try {
			HashMap<String, Object> payMap = new HashMap<>();
			if ("SCAN_WEIXIN".equals(payMethodStr)) {
				// 微信扫码支付正扫
				payMap.put("limitPay", limitPay);
				payMap.put("payType", payType); // 非贷记卡：W02, 借、贷卡：W01
				payMap.put("amount", amount); // 分
				payMethod.put("SCAN_WEIXIN", payMap);
			}else if ("WECHATPAY_MiniProgram".equals(payMethodStr)) {
				// 微信小程序支付
				payMap.put("limitPay", limitPay);
				payMap.put("amount", amount); // 分
				payMap.put("acct", wxOpenId);
				payMethod.put("WECHATPAY_MINIPROGRAM", payMap);
			}else if ("SCAN_ALIPAY".equals(payMethodStr)) {
				// 支付宝支付(正扫)
				payMap.put("limitPay", limitPay);
				payMap.put("amount", amount); // 分
				payMethod.put("SCAN_ALIPAY", payMap);
			}else if ("CODEPAY_W".equals(payMethodStr)) {
				// 微信刷卡支付（被扫）
				payMap.put("limitPay", limitPay); // 非贷记卡：no_credit; 借、贷记卡：””
				payMap.put("amount", amount); // 分
				payMap.put("authcode", authCode);
				payMethod.put("CODEPAY_VSP", payMap);
			} else if ("CODEPAY_A".equals(payMethodStr)) {
				// 支付宝刷卡支付(被扫)
				payMap.put("limitPay", limitPay);
				payMap.put("amount", amount); // 分
				payMap.put("authcode", authCode);
				payMethod.put("CODEPAY_VSP", payMap);
			} else if("WECHAT_PUBLIC".equals(payMethodStr)){
				//微信js支付（公众号）
				payMap.put("limitPay", limitPay);
				payMap.put("amount", amount); // 分
				payMap.put("acct", wxOpenId);
				payMethod.put("WECHAT_PUBLIC", payMap);
			}
			request.put("payerId", payerId);
			request.put("recieverList", recieverList);
			request.put("bizOrderNo", bizOrderNo);
			request.put("tradeCode", "3001"); //消费代收
			request.put("amount", amount);
			//request.put("accountSetNo", accountSetNo);
			
			request.put("fee", 0L);
			request.put("validateType", 0); // 0: 无验证；1：短信；2：支付密码
//			request.put("frontUrl", frontUrl);//前台通知地址
			request.put("backUrl", backUrl);// 后台通知地址
	
			request.put("ordErexpireDatetime", ordErexpireDatetime);
			request.put("payMethod", JSONObject.toJSON(payMethod));
			
			request.put("industryCode", "2414");
			request.put("industryName", "个护化妆");
			request.put("source", 2L);
			request.put("summary", "AUTO-TEST");
			request.put("extendInfo", "AUTO-TEST");
			

			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if (status != null && status.equals("OK")) {
				result.put("status", "OK");
				result.put("code", "0");
				result.put("message", "SUCCESS");
				result.put("res", res);
				payStatus = resp.getJSONObject("signedValue").getString("payStatus");
				payFailMessage = resp.getJSONObject("signedValue").getString("payFailMessage");
//				orderNo = resp.getJSONObject("signedValue").getString("orderNo");
//				tradeNo = resp.getJSONObject("signedValue").getString("tradeNo");
//				payCode = resp.getJSONObject("signedValue").getString("payCode");
				extendInfo = resp.getJSONObject("signedValue").getString("extendInfo");
				payInfo = resp.getJSONObject("signedValue").getString("payInfo");
				if(payMethodStr.equals("WECHATPAY_MiniProgram")||payMethodStr.equals("WECHAT_PUBLIC")) {
					appId = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("appId");
					timeStamp = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("timeStamp");
					nonceStr = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("nonceStr");
					packageStr = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("package");
					signType = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("signType");
					paySign = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("paySign");
					prepayid = packageStr.split("=")[1];
				}
				log.info("API[agentCollectApplySimplify SUCCESS!]");
			} else {
				result.put("status", "error");
				result.put("code", resp.getString("errorCode"));
				result.put("message", resp.getString("message"));
				result.put("res", res);
				log.error("API_ERROR[agentCollectApplySimplify RESULT=[" + resp.getString("errorCode") + ", "
						+ resp.getString("message") + "]]");
			}
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
			// e.printStackTrace();
		}
//		result.put("payerId", payerId);
		result.put("bizOrderNo", bizOrderNo);
//		result.put("orderNo", orderNo);
//		result.put("tradeNo", tradeNo);
//		result.put("payCode", payCode);
//		result.put("extendInfo", extendInfo);
		result.put("payInfo", payInfo);
		result.put("payStatus", payStatus);
		result.put("payFailMessage", payFailMessage);
		//wechat pay must info
		result.put("prepayid",prepayid);
		result.put("appId", appId);
		result.put("packageStr", packageStr);
		result.put("nonceStr", nonceStr);
		result.put("timeStamp", timeStamp);
		result.put("paySign", paySign);
		result.put("signType", signType);
		
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderAPI: agentCollectApplySimplify end================[elapse: " + elapse + " ms]");
		return result;
	}

	@Override
	public HashMap<String, String> signalAgentPay(List<CollectPay> collectPays, String bizUserId) {
		// TODO Auto-generated method stub
		log.info("================OrderAPI: signalAgentPay begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "signalAgentPay");
		HashMap<String, Object> payMethod = new HashMap<>();
		try {
			// 源托管代收订单付款信息
			JSONArray collectPayList = new JSONArray();
			Long amount = new Long(0);
			
			for(CollectPay collectPay:collectPays ) {
				HashMap<String, Object> collect = new HashMap<>();
				collect.put("bizOrderNo", collectPay.getBizOrderNo());
				collect.put("amount", collectPay.getAmount());
				collectPayList.add(new JSONObject(collect));
				amount = amount+collectPay.getAmount();
			}
//			List<SplitRuleDTO> splitRuleDTOs = new ArrayList<SplitRuleDTO>();
//			SplitRuleDTO splitRuleDTO = new SplitRuleDTO();
//			//设置分账规则，取千分之6
//			BigDecimal amountBigDecimal = new BigDecimal(0);
//			amountBigDecimal = new BigDecimal(amount).multiply(new BigDecimal(6));
//			amountBigDecimal = amountBigDecimal.divide(new BigDecimal(1000));
//			long splitamount = amountBigDecimal.longValue();
//			splitRuleDTO.setAmount(splitamount);
//			splitRuleDTOs.add(splitRuleDTO);
//			if(amount>=200) {
//				//如果金额大于200分需要收取手续费千分之六
//				BigDecimal fee = new BigDecimal(0);
//				fee = new BigDecimal(amount).multiply(new BigDecimal(6));
//				//四舍五入
//				fee = fee.divide(new BigDecimal(1000),BigDecimal.ROUND_HALF_UP);
//				long feeamount = fee.longValue();
//				request.put("fee", feeamount);
//			}else {
//				request.put("fee", 0L);
//			}
			request.put("fee", 0L);
			request.put("bizOrderNo", "DF"+System.currentTimeMillis());
			request.put("collectPayList", collectPayList);
			request.put("bizUserId", bizUserId);	
			request.put("accountSetNo", accountSetNo);
			request.put("backUrl", "http://172.16.190.46:8080/yuncallback/mock/notify?");
			request.put("amount", amount);
//			request.put("splitRuleList", splitRuleDTOs);
			request.put("tradeCode", "4001");
			request.put("summary", "signalAgentPay");
			request.put("extendInfo", "this is extendInfo");
			
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				result.put("res", res);
				result.put("fee", request.get("fee").toString());
				log.info("API[signalAgentPay SUCCESS!]");
			} else {
				result.put("res", res);
				log.error("API_ERROR[signalAgentPay RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderAPI: signalAgentPay end================[elapse: " + elapse + " ms]");
		return result;
	}

	@Override
	public HashMap<String, String> refund(String bizUserId, String oriBizOrderNo, Long amount,String backUrl) {
		// TODO Auto-generated method stub
		log.info("================OrderAPI: refund begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "refund");
		HashMap<String, Object> payMethod = new HashMap<>();
		String bizOrderNo = "RF"+System.currentTimeMillis();
		String payStatus = "";
		String payFailMessage = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("bizOrderNo", bizOrderNo);
			request.put("oriBizOrderNo", oriBizOrderNo);
			request.put("amount", amount);
			request.put("refundType", "D0");//实时退款
			request.put("feeAmount", 0L);
			request.put("backUrl",backUrl);
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				result.put("bizOrderNo",bizOrderNo);
				result.put("status","OK");
				payStatus = resp.getJSONObject("signedValue").getString("payStatus");
				payFailMessage = resp.getJSONObject("signedValue").getString("payFailMessage");
				result.put("payStatus",payStatus);
				result.put("payFailMessage",payFailMessage);
				result.put("res", res);
				log.info("API[refund SUCCESS!]");
			} else {
				result.put("status","error");
				result.put("status",resp.getString("message"));
				result.put("res", res);
				log.error("API_ERROR[refund RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderAPI: refund end================[elapse: " + elapse + " ms]");
		return result;
	}

	@Override
	public HashMap<String, String> withdrawApply(String bizUserId, Long amount, int feeTax,String backUrl,
			String bankCardNo) {
		// TODO Auto-generated method stub
		log.info("================OrderAPI: withdrawApply begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "withdrawApply");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, 15);
		Date date = calendar.getTime();
		String ordErexpireDatetime = sdf.format(date);
		String payStatus = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("bizOrderNo", "WR"+System.currentTimeMillis());
			request.put("accountSetNo", accountSetNo);
			request.put("amount", amount);
			request.put("fee", feeTax);//手续费和税务
			request.put("validateType", 0L);
			request.put("backUrl", backUrl);
			request.put("ordErexpireDatetime", ordErexpireDatetime);
			request.put("bankCardNo", RSAUtil.encrypt(bankCardNo));
			request.put("bankCardPro", 0L);
			request.put("withdrawType", "D0");
			request.put("industryCode", "2414");
			request.put("industryName", "个护化妆");
			request.put("source", 2L);
			request.put("summary", "withdraw");
			request.put("extendInfo", "this is extendInfo");			
			
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				result.put("status", "OK");
				result.put("res", res);
				payStatus = resp.getJSONObject("signedValue").getString("payStatus");
				log.info("API[withdrawApply SUCCESS!]");
			} else {
				result.put("status", "error");
				result.put("message", resp.getString("message"));
				result.put("res", res);
				log.error("API_ERROR[withdrawApply RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
			
		} catch (final Exception e) {
			e.printStackTrace();
		}
		result.put("bizOrderNo", request.get("bizOrderNo").toString());
		result.put("payStatus", payStatus);
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderAPI: withdrawApply end================[elapse: " + elapse + " ms]");
		return result;
	}

	@Override
	public HashMap<String, String> getOrderDetail(String bizOrderNo) {
		// TODO Auto-generated method stub
		log.info("================OrderAPI: refund begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "getOrderDetail");
		HashMap<String, Object> payMethod = new HashMap<>();
		try {
			request.put("bizOrderNo", bizOrderNo);
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				result.put("res", res);
				log.info("API[refund SUCCESS!]");
			} else {
				result.put("res", res);
				log.error("API_ERROR[refund RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderAPI: refund end================[elapse: " + elapse + " ms]");
		return result;
	}

	@Override
	public String unbindBankCard(String bizUserId, String cardNo) {
		// TODO Auto-generated method stub
		log.info("================MemberService: unbindBankCard begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("MemberService", "unbindBankCard");
		HashMap<String, Object> payMethod = new HashMap<>();
		String status = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("cardNo", cardNo);
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				log.info("API[unbindBankCard SUCCESS!]");
			} else {
				log.error("API_ERROR[unbindBankCard RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================MemberService: unbindBankCard end================[elapse: " + elapse + " ms]");
		return status;
	}
	
	@Override
	public HashMap<String, String> queryBalance(String bizUserId) {
		log.info("================OrderService: queryBalance begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "queryBalance");
		HashMap<String, Object> payMethod = new HashMap<>();
		String status = "";
		try {
			request.put("bizUserId", bizUserId);
			request.put("accountSetNo", accountSetNo);
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			status = resp.getString("status");
			if(status != null && status.equals("OK")) {
				result.put("status", "OK");
				result.put("allAmount", resp.getJSONObject("signedValue").getString("allAmount"));
				result.put("freezenAmount", resp.getJSONObject("signedValue").getString("freezenAmount"));
				log.info("API[queryBalance SUCCESS!]");
			} else {
				result.put("status", "error");
				result.put("message", resp.getString("message"));
				log.error("API_ERROR[queryBalance RESULT=["+resp.getString("errorCode")+", "+resp.getString("message")+"]]");
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderService: queryBalance end================[elapse: " + elapse + " ms]");
		return result;
	}

	@Override
	public HashMap<String, String> consumeApply(String payerId, String recieverId, Long amount, String backUrl,
			String payMethodStr,String openId,int expiredTime) {
		// TODO Auto-generated method stub
		log.info("================OrderAPI: consumeApply begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "consumeApply");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.SECOND, expiredTime);
		Date date = calendar.getTime();
		String ordErexpireDatetime = sdf.format(date);
		HashMap<String, Object> payMethod = new HashMap<>();
		String bizOrderNo = "SF" + System.currentTimeMillis();
		String payStatus = "";
		String payFailMessage = "";
		String orderNo = "";
		String payCode = "";
		String tradeNo = "";
		String payInfo = "";
		String extendInfo = "";
		//微信支付返回信息
		String appId = "";
		String packageStr = "";
		String prepayid = "";
		String nonceStr = "";
		String timeStamp = "";
		String paySign = "";
		String signType = "";
		String limitPay = ""; //空字符串，可以贷记卡，不用借贷卡--no_credit
		String payType = "W02"; //默认不用借贷卡
		try {
			JSONArray balancePay = new JSONArray();
			JSONObject payMap = new JSONObject();
			if ("BALANCE".equals(payMethodStr)) {
				// 账户余额
				payMap.put("accountSetNo", accountSetNo);
				payMap.put("amount", amount); // 分
				balancePay.add(payMap);
				payMethod.put("BALANCE", balancePay);
			}else if("WECHAT_PUBLIC".equals(payMethodStr)){
				//微信js支付（公众号）
				payMap.put("limitPay", limitPay);
				payMap.put("amount", amount); // 分
				payMap.put("acct", openId);
				payMethod.put("WECHAT_PUBLIC", payMap);
			}if ("SCAN_WEIXIN".equals(payMethodStr)) {
				// 微信扫码支付正扫
				payMap.put("limitPay", limitPay);
				payMap.put("payType", payType); // 非贷记卡：W02, 借、贷卡：W01
				payMap.put("amount", amount); // 分
				payMethod.put("SCAN_WEIXIN", payMap);
			}
			
			//设置分账规则
//			List<SplitRuleDTO> splitRuleDTOs = new ArrayList<SplitRuleDTO>();
//			SplitRuleDTO splitRuleDTO = new SplitRuleDTO();
//			BigDecimal amountBigDecimal = new BigDecimal(0);
//			amountBigDecimal = new BigDecimal(amount).multiply(new BigDecimal(6));
//			amountBigDecimal = amountBigDecimal.divide(new BigDecimal(1000));
//			long splitamount = amountBigDecimal.longValue();
//			splitRuleDTO.setAmount(splitamount);
//			splitRuleDTOs.add(splitRuleDTO);
//			request.put("splitRuleList", splitRuleDTOs);
			
			request.put("payerId", payerId);
			request.put("recieverId", recieverId);
			request.put("bizOrderNo", bizOrderNo);
			request.put("amount", amount);
			
			request.put("fee", 0L);
			request.put("validateType", 0); // 0: 无验证；1：短信；2：支付密码
			request.put("backUrl", backUrl);// 后台通知地址
	
			request.put("ordErexpireDatetime", ordErexpireDatetime);
			request.put("payMethod", payMethod);
			
			request.put("industryCode", "2414");
			request.put("industryName", "个护化妆");
			request.put("source", 2L);
			request.put("summary", "AUTO-TEST");
			request.put("extendInfo", "AUTO-TEST");
			
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if (status != null && status.equals("OK")) {
				result.put("status", "OK");
				result.put("code", "0");
				result.put("message", "SUCCESS");
				result.put("res", res);
				payStatus = resp.getJSONObject("signedValue").getString("payStatus");
				payFailMessage = resp.getJSONObject("signedValue").getString("payFailMessage");
				orderNo = resp.getJSONObject("signedValue").getString("orderNo");
				tradeNo = resp.getJSONObject("signedValue").getString("tradeNo");
				payCode = resp.getJSONObject("signedValue").getString("payCode");
				extendInfo = resp.getJSONObject("signedValue").getString("extendInfo");
				payInfo = resp.getJSONObject("signedValue").getString("payInfo");
				if(payMethodStr.equals("WECHAT_PUBLIC")) {
					appId = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("appId");
					timeStamp = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("timeStamp");
					nonceStr = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("nonceStr");
					packageStr = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("package");
					signType = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("signType");
					paySign = resp.getJSONObject("signedValue").getJSONObject("payInfo").getString("paySign");
					prepayid = packageStr.split("=")[1];
				}
				log.info("API[consumeApply SUCCESS!]");
			} else {
				result.put("status", "error");
				result.put("code", resp.getString("errorCode"));
				result.put("message", resp.getString("message"));
				result.put("res", res);
				log.error("API_ERROR[consumeApply RESULT=[" + resp.getString("errorCode") + ", "
						+ resp.getString("message") + "]]");
			}
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
			// e.printStackTrace();
		}
		result.put("payerId", payerId);
		result.put("bizOrderNo", bizOrderNo);
		result.put("orderNo", orderNo);
		result.put("tradeNo", tradeNo);
		result.put("payCode", payCode);
		result.put("extendInfo", extendInfo);
		result.put("payInfo", payInfo);
		result.put("payStatus", payStatus);
		result.put("payFailMessage", payFailMessage);
		//微信支付
		result.put("prepayid",prepayid);
		result.put("appId", appId);
		result.put("packageStr", packageStr);
		result.put("nonceStr", nonceStr);
		result.put("timeStamp", timeStamp);
		result.put("paySign", paySign);
		result.put("signType", signType);
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderAPI: consumeApply end================[elapse: " + elapse + " ms]");
		return result;
	}

	@Override
	public Map<String, String> applicationTransfer( String targetBizUserId, Long amount) {
		log.info("================OrderAPI: applicationTransfer begin================");
		long start = System.currentTimeMillis();
		HashMap<String, String> result = new HashMap<String, String>();
		final YunRequest request = new YunRequest("OrderService", "applicationTransfer");
		String bizTransferNo = "TF" + System.currentTimeMillis();
		request.put("bizTransferNo", bizTransferNo);
		request.put("sourceAccountSetNo", normAccountSetNo);
		request.put("targetBizUserId", targetBizUserId);
		request.put("targetAccountSetNo", accountSetNo);
		request.put("amount", amount);
		request.put("extendInfo", "AUTO-TEST");
		try {
			String res = YunClient.request(request);
			JSONObject resp = JSON.parseObject(res);
			String status = resp.getString("status");
			if (status != null && status.equals("OK")) {
				result.put("status", "OK");
				result.put("code", "0");
				result.put("message", "SUCCESS");
				result.put("res", res);
				result.put("normAccountSetNo", normAccountSetNo);
				log.info("API[consumeApply SUCCESS!]");
			} else {
				result.put("status", "error");
				result.put("code", resp.getString("errorCode"));
				result.put("message", resp.getString("message"));
				result.put("res", res);
				log.error("API_ERROR[consumeApply RESULT=[" + resp.getString("errorCode") + ", "
						+ resp.getString("message") + "]]");
			}
		} catch (final Exception e) {
			log.error("EXCEPTION", e);
			// e.printStackTrace();
		}
		result.put("bizTransferNo",bizTransferNo);
		long end = System.currentTimeMillis();
		long elapse = end - start;
		log.info("================OrderAPI: applicationTransfer end================[elapse: " + elapse + " ms]");
		return result;
	}
}
